package com.teacher.util;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.multipart.MultipartFile;

public class Upload {

	/**
	 * Spring MultiPart文件上传工具
	 * 
	 * @param file
	 *            要上传的文件
	 * @param dir
	 *            基于服务器根目录的子目录
	 * @throws IllegalStateException
	 * @throws IOException
	 * 
	 * @return 返回文件在服务器上的路径
	 */
	public static String Uploadfile(MultipartFile file, String dir,
			HttpServletRequest request) throws IllegalStateException,
			IOException {
		File directory = new File(request.getServletContext().getRealPath("/" + dir));
		if (!directory.exists()) {
			directory.mkdirs();
		}
		String path = request.getContextPath();
		String basePath = request.getScheme() + "://" + request.getServerName()
				+ ":" + request.getServerPort() + path + "/";
		String fileName = "";
		fileName += DateUtils.formatDate(new Date(), "YYYYMMdd")
				+ new Random().nextInt(10000);
		String filePath = request.getServletContext().getRealPath("/" + dir)
				+ File.separator + fileName
				+ getExtendName(file.getOriginalFilename());
		file.transferTo(new File(filePath));
		String result = basePath + dir + "/" + fileName
				+ getExtendName(file.getOriginalFilename());
		return result;
	}

	private static String getExtendName(String filename) {
		String extName = "";
		extName = filename.substring(filename.lastIndexOf("."));
		return extName;
	}
}
